package com.li.my_tiny_spring.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.li.my_tiny_spring.exception.impl.MyIllegalStateException;

public class JdkDynamicAopProxy {

	private AdvisedSupport advisedSupport;

	public JdkDynamicAopProxy(AdvisedSupport advisedSupport) {
		this.advisedSupport = advisedSupport;
	}

	public Object getProxy() {
		TargetSource targetSource = advisedSupport.getTargetSource();
		InvocationHandler myInvocationHandler = new MyInvocationHandler(targetSource.getTarget(),advisedSupport.getMethodInterceptor());
		return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), targetSource.getImplClass().getInterfaces(),
			myInvocationHandler);
	}

	private static class MyInvocationHandler implements InvocationHandler {

		private final Object target;
		private final MethodInterceptor methodInterceptor;

		private MyInvocationHandler(Object target,MethodInterceptor methodInterceptor) {
			this.target = target;
			this.methodInterceptor = methodInterceptor;
		}

		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			try {
				methodInterceptor.before();
				Object result = method.invoke(target, args);
				methodInterceptor.after();
				return result;
			}catch(Exception e) {
				throw new MyIllegalStateException(e);
			}finally {
				methodInterceptor.afterFinal();
			}
		}

	}

}
